package ru.spbau.database.group3.queryEvaluator;

import ru.spbau.database.group3.engine.DatabaseEngine;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: stas
 * Date: 1/29/13
 * Time: 2:11 PM
 */
public class InsertInstruction implements Instruction {

    public InsertInstruction(String tableName, List<String> colNames, List<String> values) {
        this.tableName = tableName;
        this.values = getValues(values);
    }

    @Override
    public QueryResult handle(DatabaseEngine engine) throws IOException, ClassNotFoundException {
        return engine.insert(tableName, values);
    }

    private List<Object> getValues(List<String> stringValues) {
        ArrayList<Object> values = new ArrayList<Object>();
        for(String value : stringValues) {
            values.add(getValue(value));
        }
        return values;
    }

    private Object getValue(String value) {
        if(value.matches("\".*\"")) {
            return value.substring(1, value.length()-1);
        } else {
            if(value.indexOf('.') > 0) {
                return Double.parseDouble(value);
            } else {
                return Integer.parseInt(value);
            }
        }
    }


    private String tableName;
    private List<Object> values;
}
